package com.adam.example.aggregation.pipeline;

import com.adam.example.TransportClientHolder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.histogram.DateHistogramAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.histogram.DateHistogramInterval;
import org.elasticsearch.search.aggregations.bucket.histogram.Histogram;
import org.elasticsearch.search.aggregations.metrics.sum.Sum;
import org.elasticsearch.search.aggregations.pipeline.PipelineAggregatorBuilders;
import org.elasticsearch.search.aggregations.pipeline.bucketmetrics.stats.extended.ExtendedStatsBucket;
import org.elasticsearch.search.aggregations.pipeline.bucketmetrics.stats.extended.ExtendedStatsBucketPipelineAggregationBuilder;

import java.net.UnknownHostException;

public class ExtendedStatsBucketAggregationExample {

    public static void main(String[] args) throws UnknownHostException {
        TransportClient transportClient = TransportClientHolder.getInstance().getTransportClient();

        DateHistogramAggregationBuilder dateHistogramAggregationBuilder = AggregationBuilders
                .dateHistogram("sales_per_month").field("sales_date")
                .dateHistogramInterval(DateHistogramInterval.MONTH)
                .subAggregation(AggregationBuilders.sum("sales").field("sales_price"));
        ExtendedStatsBucketPipelineAggregationBuilder extendedStatsBucketPipelineAggregationBuilder = PipelineAggregatorBuilders
                .extendedStatsBucket("agg", "sales_per_month>sales");
        SearchResponse searchResponse = transportClient.prepareSearch("test")
                .setTypes("sales").setSize(0).addAggregation(dateHistogramAggregationBuilder)
                .addAggregation(extendedStatsBucketPipelineAggregationBuilder).get();
        Histogram histogram = searchResponse.getAggregations().get("sales_per_month");
        for(Histogram.Bucket bucket: histogram.getBuckets()) {
            Sum sum = bucket.getAggregations().get("sales");
            System.out.println(bucket.getKey() + ":" + sum.getValue());
            //getKey返回的是org.joda.time.DateTime类型
        }
        ExtendedStatsBucket statsBucket = searchResponse.getAggregations().get("agg");
        System.out.println("最大月销售额:" + statsBucket.getMax());
        System.out.println("最小月销售额:" + statsBucket.getMin());
        System.out.println("各月份累计月销售额:" + statsBucket.getSum());
        System.out.println("平均月销售额:" + statsBucket.getAvg());
        System.out.println("月份数:" + statsBucket.getCount());
        System.out.println("标准差：" + statsBucket.getStdDeviation());
        System.out.println("平方和：" + statsBucket.getSumOfSquares());
        System.out.println("方差：" + statsBucket.getVariance());

        transportClient.close();
    }

}
